﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;

namespace TaskMasterByQuartz.Infrastructure.Initializer
{
    public static class QuartzServiceExtensions
    {
        public static void AddCustomQuartz(this WebApplicationBuilder builder)
        {


            // 来自 appsettings.json 的基本配置
            builder.Services.Configure<QuartzOptions>(builder.Configuration.GetSection("Quartz"));

            builder.Services.Configure<QuartzOptions>(options =>
            {
                options.Scheduling.IgnoreDuplicates = true; // default: false
                options.Scheduling.OverWriteExistingData = true; // default: true
            });


            builder.Services.AddQuartz(q =>
            {
                ////调度程序唯一识别码
                //q.SchedulerId = "Quartz_Web";
                // 控制在调度程序关闭时正在运行的作业是否中断 
                q.InterruptJobsOnShutdown = true;
                // when QuartzHostedServiceOptions.WaitForJobsToComplete = true or scheduler.Shutdown(waitForJobsToComplete: true)
                q.InterruptJobsOnShutdownWithWait = true;
                // 允许调度程序一个批次获取的最大触发器数量
                //数字越大,触发效率越高,但会导致集群时的负载均衡不平衡
                q.MaxBatchSize = 5;
                //调度程序名称
                //q.SchedulerName = "定时服务调度程序";
                //Microsoft DI集成
                q.UseMicrosoftDependencyInjectionJobFactory();

                //使用默认线程池 最大并发数 10
                q.UseDefaultThreadPool(maxConcurrency: 10);
                // auto-interrupt long-running job
                q.UseJobAutoInterrupt(options =>
                {
                    // this is the default
                    options.DefaultMaxRunTime = TimeSpan.FromMinutes(5);
                });
                // 时区转换器 可以处理 Windows/Linux 差异的转换器转换时区 
                q.UseTimeZoneConverter();
                //使用持久化
                q.UsePersistentStore(option =>
                {
                    //设置是否在 JobDataMaps中仅处理字符串
                    option.UseProperties = true;
                    //设置数据库重试时间为20秒 默认是15秒
                    option.RetryInterval = TimeSpan.FromSeconds(20);
                    //使用SQLServer数据库
                    option.UseSqlServer(sqlServer =>
                    {
                        sqlServer.ConnectionString = builder.Configuration.GetConnectionString("QuartzConnStr");
                        // this is the default
                        sqlServer.TablePrefix = "QRTZ_";
                    });

                    option.UseJsonSerializer();
                    //    //TODO 调度器
                    //    //集群化设置
                    //    //option.UseClustering(c =>
                    //    //{
                    //    //    c.CheckinMisfireThreshold = TimeSpan.FromSeconds(20);
                    //    //    c.CheckinInterval = TimeSpan.FromSeconds(10);
                    //    //});
                    builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
                });
            });

            // Quartz.Extensions.Hosting 允许您触发处理调度程序生命周期的后台服务
            builder.Services.AddQuartzHostedService(options =>
            {
                // 关闭时，我们希望作业优雅地完成
                options.WaitForJobsToComplete = true;
            });


        }
    }
}
